﻿using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace _5E.Utils.DbHelper.EasySQL.Creator
{
    /// <summary>
    /// 程序说明：解析条件
    /// 创建作者：ahl5esoft
    /// 创建时间：2012-04-17
    /// </summary>
    class ParseCondition
    {
        #region 变量

        private const string RELATIONAL_OPERATOR_FORMAT = "{0} {1} :{2}";

        private static Regex[] s_ConditionRegexs = new[] 
        { 
            new Regex(@"(<=)(\w+)"),
            new Regex(@"(>=)(\w+)"),
            new Regex(@"(<)(\w+)"),
            new Regex(@"(=)(\w+)"),
            new Regex(@"(>)(\w+)")
        };

        #endregion

        #region 转换

        public static string ToWhere(string condition, Dictionary<string, string> allColumns)
        {
            var where = string.Empty;
            if (!string.IsNullOrEmpty(condition))
            {
                where = condition;
                foreach (var reg in s_ConditionRegexs)
                {
                    where = reg.Replace(where, match =>
                    {
                        var propertyName = match.Groups[2].Value;
                        var columnName = BaseCreator.GetColumnName(propertyName, allColumns);
                        var relational = match.Groups[1].Value;
                        return string.Format(RELATIONAL_OPERATOR_FORMAT, columnName, relational, propertyName);
                    });
                }
                where = string.Format("WHERE {0}", where);
            }
            return where;
        }

        #endregion
    }
}
